package de.graffiti.beans;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.imageio.ImageIO;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import de.graffiti.entities.Content;
import de.graffiti.entities.Wallitem;
import de.graffiti.entities.Wallpaper;
import de.graffiti.interfaces.WallItemService;

@Stateless
public class WallItemServiceBean implements WallItemService
{

	@PersistenceContext(unitName = "graffiti")
	private EntityManager em;
	private int height;
	private int width;

	@Override
	public String uploadItem(int wallpaperid, String sessionid, String author, String content, String contenttype, int height, int width, int xpos, int ypos)
	{

		Content con = new Content();
		con.setContenttype(contenttype);
		con.setData(content.getBytes());
		em.persist(con);
		em.flush();

		Wallitem item = new Wallitem();
		item.setAuthor(author);
		item.setWallpaperid(wallpaperid);
		item.setStatus("a");
		item.setHeight(height);
		item.setWidth(width);
		item.setXpos(xpos);
		item.setYpos(ypos);
		item.setCreationdate(new Date());
		item.setContentid(con.getContentid());
		em.persist(item);

		updatePicture(wallpaperid, content.getBytes());

		return "success";

	}

	public List getAllWallitems(int wallpaperid)
	{
		Query query = em.createNamedQuery("Wallitem.findByWallpaper");
		query.setParameter("status", "a");
		query.setParameter("wallpaperid", wallpaperid);
		return query.getResultList();

	}

	public void updatePicture(int wallpaperid, byte[] wallitem)
	{

		Wallpaper wp = getWallpaper(wallpaperid);

		if (wp != null)
		{
			this.height = wp.getHeight();
			this.width = wp.getWidth();
			Content con = getContent(wp.getPaintedcontentid());

			try
			{

				byte[] wallpaper = getContent(wp.getPaintedcontentid()).getData();
				byte[] result = addWallitem(wallpaper, transcodeSvgToPng(wallitem), wp.getHeight(), wp.getWidth());
				con.setData(result);
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			con.setContenttype("image/jpg");
			em.persist(con);
			em.flush();
		}

	}

	public byte[] transcodeSvgToPng(byte[] svgData)
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		PNGTranscoder t = new PNGTranscoder();

		try
		{
			TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgData));
			TranscoderOutput output = new TranscoderOutput(out);
			t.transcode(input, output);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return out.toByteArray();
	}

	public byte[] transcodeSvgToJpg(byte[] svgData)
	{

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		JPEGTranscoder t = new JPEGTranscoder();
		t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.8));

		try
		{
			TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgData));
			TranscoderOutput output = new TranscoderOutput(out);
			t.transcode(input, output);

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return out.toByteArray();
	}

	public byte[] addWallitem(byte[] old, byte[] wallitem, int height, int width) throws IOException
	{

		BufferedImage img = ImageIO.read(new ByteArrayInputStream(old));
		BufferedImage img2 = ImageIO.read(new ByteArrayInputStream(wallitem));

		BufferedImage bufferedImage = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);

		Graphics graphics = bufferedImage.createGraphics();
		graphics.drawImage(img, 0, 0, null);
		graphics.drawImage(img2, 0, 0, null);
		//		 
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		//		 
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
		encoder.setJPEGEncodeParam(param);
		encoder.encode(bufferedImage);

		return os.toByteArray();

	}

	public Wallpaper getWallpaper(int id)
	{
		if (em != null)
		{
			Query query = em.createNamedQuery("Wallpaper.findById");
			query.setParameter("wallpaperid", id);
			if (query.getResultList().size() > 0)
			{
				return (Wallpaper) query.getResultList().get(0);
			}
		}
		return null;

	}

	public Content getContent(int id)
	{
		if (em != null)
		{
			Query query = em.createNamedQuery("Content.findById");
			query.setParameter("contentid", id);
			if (query.getResultList().size() > 0)
			{
				return (Content) query.getResultList().get(0);
			}
		}
		return null;

	}

}
